<template>
  <div>
    <el-upload
        action=""
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="successAdd"
        :before-upload="beforeAvatarUpload"
        :http-request="ossUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { sysAjax } from 'Ajax'
const axios = require('axios')

export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  // props:['width','height'],
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
      console.log('url', this.dialogImageUrl)
    },
    successAdd() {

    },
    beforeAvatarUpload(file) {
      // const width = 1024
      // const height = 1024
      // // 上传图片前处理函数
      // const isSize = new Promise(function(resolve, reject) {
      //   const _URL = window.URL || window.webkitURL
      //   const image = new Image()
      //   image.onload = function() {
      //     const valid = image.width === width && image.height === height
      //     valid ? resolve() : reject()
      //   }
      //   image.src = _URL.createObjectURL(file)
      // }).then(() => {
      //       return file
      //     }, () => {
      //       this.$message.error('上传图片尺寸不符合,只能是' + width + '*' + height + '!')
      //       return Promise.reject()
      //     }
      // )
      // return isSize
    },
    ossUpload(data) {
      const file = data.file
      console.log(file)

      const index = file.name.indexOf('.')
      const nameEnd = file.name.substr(index)

      sysAjax.getOssPolicy().then(res => {
        console.log('policy', res)

        const nameStart = new Date().getTime() + '' + Math.ceil(Math.random() * 100)
        const name = '/' + nameStart + nameEnd

        const sendData = new FormData()
        sendData.append('OSSAccessKeyId', res.accessKeyId)
        sendData.append('policy', res.policy)
        sendData.append('signature', res.signature)
        // sendData.append('keys', res.dir)
        sendData.append('key', res.dir + name)
        sendData.append('success_action_status', '200') // 指定返回的状态码
        sendData.append('callback', res.callback)
        sendData.append('type', 'image/jpeg')
        sendData.append('file', file)
        axios.post(res.host, sendData, {
          'Content-Type': 'multipart/form-data'
        }).then(ossRes => {
          console.log('file', ossRes.data.data)
          console.log('url', ossRes.data.data.filename)
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
